package net.zoneland.knowledge.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 动态定时任务的线程池.
 */
@Configuration
@ThreadSafe
public class TaskSchedulerPoolConfig {

    /**
     * 核心线程
     */
    @Value("${spring.thread-pool.poolSize:10}")
    private int poolSize;

    @Value("${spring.thread-pool.threadNamePrefix:scheduled-pool-}")
    private String threadNamePrefix;

    @Value("${spring.thread-pool.awaitTermination:60}")
    private int awaitTermination; //挂壁时间

    private static ThreadPoolTaskScheduler taskScheduler;

    @Bean(name = "taskSchedulerPoolExecutor")
    public synchronized ThreadPoolTaskScheduler taskSchedulerPoolExecutor(){

        if(taskScheduler == null){
            taskScheduler = new ThreadPoolTaskScheduler();
            // 设置线程池中，线程的命名前缀，方便识别哪些线程是定时任务的
            taskScheduler.setThreadNamePrefix(threadNamePrefix);
            taskScheduler.setPoolSize(poolSize);
            taskScheduler.setAwaitTerminationSeconds(awaitTermination); // 挂壁的时间为60s
            // 设置为false,关闭线程池中的任务时,直接执行shutdownNow() 延时关闭 开启
            taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
            taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); //线程池对拒绝任务（无线程可用的）的处理策略
            taskScheduler.initialize(); //初始化
        }

        return taskScheduler;
    }

}
